import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';
import 'package:provider/provider.dart';

class FeedBackPage extends StatefulWidget {
  @override
  State<FeedBackPage> createState() => _FeedBackPageState();
}

class _FeedBackPageState extends State<FeedBackPage> {
  TextEditingController _questionController = TextEditingController();
  TextEditingController _emailController = TextEditingController();
  final FocusNode _questionFocusNode = FocusNode();
  final FocusNode _emailFocusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: commonAppBar(appLocalForContext(context).feedbackTitle),
        body: GestureDetector(
          onTap: () {
            _questionFocusNode.unfocus();
            _emailFocusNode.unfocus();
          },
          child: ChangeNotifierProvider(
            create: (context) => FeedBackProvider(),
            child: Container(
              color: Color(0xfff2f2f2),
              padding: EdgeInsets.only(left: 16, right: 16),
              width: double.infinity,
              height: double.infinity,
              child: Column(
                children: [
                  Expanded(
                    child: KeyboardAvoider(
                      autoScroll: true,
                      child: SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(
                              height: 10,
                            ),
                            Text(appLocalForContext(context)
                                .feedbackQuestionTitle),
                            SizedBox(
                              height: 10,
                            ),
                            Container(
                              padding: EdgeInsets.all(2),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8),
                                color: Colors.white,
                                border: Border.all(
                                  color: Color(0x66777777),
                                  width: 1,
                                ),
                              ),
                              child: TextField(
                                cursorColor: Color(0xff3F74EF), // 设置光标颜色
                                focusNode: _questionFocusNode,
                                minLines: 10,
                                maxLines: 10,
                                controller: _questionController,
                                style: TextStyle(
                                    fontWeight: FontWeight.normal,
                                    fontSize: 14),
                                decoration: InputDecoration(
                                  hintText: appLocalForContext(context)
                                      .feedbackQuestionPlaceHolder,
                                  hintStyle: const TextStyle(
                                      color: Color(0xff999999), fontSize: 14),
                                  fillColor: Colors.white,
                                  contentPadding: const EdgeInsets.symmetric(
                                      horizontal: 16, vertical: 16),
                                  filled: true,
                                  border: InputBorder.none,
                                ),
                              ),
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Text(""),
                            SizedBox(
                              height: 10,
                            ),
                            Container(
                              padding: EdgeInsets.all(2),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8),
                                color: Colors.white,
                                border: Border.all(
                                  color: Color(0x66777777),
                                  width: 1,
                                ),
                              ),
                              child: TextField(
                                cursorColor: Color(0xff3F74EF), // 设置光标颜色
                                focusNode: _emailFocusNode,
                                minLines: 1,
                                maxLines: 1,
                                controller: _emailController,
                                style: TextStyle(
                                    fontWeight: FontWeight.normal,
                                    fontSize: 14),
                                decoration: InputDecoration(
                                    hintText: appLocalForContext(context)
                                        .enterYourEmail,
                                    hintStyle: const TextStyle(
                                        color: Color(0xff999999), fontSize: 14),
                                    fillColor: Colors.white,
                                    contentPadding: const EdgeInsets.symmetric(
                                        horizontal: 16, vertical: 16),
                                    filled: true,
                                    border: InputBorder.none),
                              ),
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            // Text("添加附件"),
                            // SizedBox(
                            //   height: 10,
                            // ),
                            // Consumer<FeedBackProvider>(
                            //   builder: (context, feedbackProvider, child) =>
                            //       GestureDetector(
                            //     onTap: () {
                            //       feedbackProvider.pickImage();
                            //     },
                            //     child: Container(
                            //       width: 110,
                            //       height: 110,
                            //       child: Stack(children: [
                            //         Container(
                            //           color: Color(0xffdddddd),
                            //         ),
                            //         Center(
                            //             child: feedbackProvider
                            //                         .feedbackImageFile !=
                            //                     null
                            //                 ? Image.file(
                            //                     feedbackProvider
                            //                         .feedbackImageFile!,
                            //                   )
                            //                 : Image.asset(
                            //                     "images/pic_add.png",
                            //                     width: 50,
                            //                     height: 50,
                            //                   ))
                            //       ]),
                            //     ),
                            //   ),
                            // )
                          ],
                        ),
                      ),
                    ),
                  ),
                  Consumer<FeedBackProvider>(
                    builder: (context, provider, child) {
                      return CupertinoButton(
                        padding: EdgeInsets.zero,
                        onPressed: () {
                          provider.feedBack(
                              _questionController.text, _emailController.text);
                        },
                        child: SafeArea(
                          child: Container(
                            width: double.infinity,
                            height: 60,
                            decoration: BoxDecoration(
                              color: Color(0xFF3F74EF),
                              borderRadius: BorderRadius.circular(30),
                            ),
                            child: Center(
                                child: Text(
                              appLocalForContext(context).feedbackSubmit,
                              style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white),
                            )),
                          ),
                        ),
                      );
                    },
                  ),
                  SizedBox(
                    height: 20,
                  )
                ],
              ),
            ),
          ),
        ));
  }
}

class FeedBackProvider extends ChangeNotifier {
  File? feedbackImageFile;
  late final ImagePicker _picker = ImagePicker();

  pickImage() async {
    try {
      XFile? imageXFile = await _picker.pickImage(
          source: ImageSource.gallery,
          imageQuality: 50,
          requestFullMetadata: false);
      feedbackImageFile = File(imageXFile!.path);
      print(imageXFile.path);
      notifyListeners();
    } catch (e) {
      print(e);
    }
  }

  feedBack(String msg, String email) async {
    final RegExp emailRegExp = RegExp(
      r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
    );

    if (!emailRegExp.hasMatch(email)) {
      EasyLoading.showToast(appLocal().enterVaildEmailName);
      return;
    }
    if (msg.isEmpty) {
      EasyLoading.showToast(appLocal().enterVaildFeedbackMsg);
      return;
    }
    EasyLoading.show();
    await HttpManager.instance
        .doRequest("/api/feedback", parameters: {"email": email, "msg": msg});
    EasyLoading.dismiss();
    EasyLoading.showToast(appLocal().feedbackSuccess);
    ARouter.instance.pagePop();
  }
}
